package com.cloudcc.mobile.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.model.MenuModel;
import com.cloudcc.cloudframe.model.MenuTabModel;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.MenuManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.mymodel.shouyerefrence;
import com.cloudcc.mobile.view.schedule.ScheduleMainActivity;
import com.cloudcc.mobile.view.web.WebViewActivtiy;
import com.litesuits.android.log.Log;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class NewMenuFilterActivity extends BaseActivity implements
		OnCheckedChangeListener {

private String mEns = RunTimeManager.getInstance().getlanguage();
	private ImageView tv1, tv2;
	private ExpandableListView expandableListView;
	private List<MenuModel> menusend;// 所有的
	private NewMymenuAdapter adapter;
//	private CheckBox check1, check2, check3, check4, check5, check6, check7,
//			check8;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		crea();
	}
	private void crea() {
		// TODO Auto-generated method stub
		setContentView(R.layout.newmenu_filter);
		tv1 = (ImageView) findViewById(R.id.menufilderheader_left);
		tv2 = (ImageView) findViewById(R.id.menufilderheader_right);
		expandableListView = (ExpandableListView) findViewById(R.id.menu_ExpandableListView);
		expandableListView.setGroupIndicator(null);
//		expandableListView.setOnGroupClickListener(NewMenuFilterActivity.this);
		addlistener();
		initlist();
	}

	@Override
	public int getLayoutId() {
		return R.layout.newmenu_filter;
	}

	// 判断选中状态
	Map<String, MenuTabModel> map = new HashMap<String, MenuTabModel>();
	// 带进来的选中状态
	private List<MenuTabModel> ShowList = new ArrayList<MenuTabModel>();;

	// 处理数据adapter
	private void initlist() {
		adddata();
		// TODO Auto-generated method stub
		menusend = new ArrayList<MenuModel>();
		menusend = (List<MenuModel>) getIntent().getSerializableExtra(
				"sort.filter");
		MenuModel menuModel = new MenuModel();
		if ("en".equals(mEns)) {
			menuModel.label = "Default";
		}else{
			menuModel.label = "默认";
	}
		
		menuModel.tab = menuTabsAll;
		try {
			menusend.add(0, menuModel);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		ShowList = (List<MenuTabModel>) getIntent().getSerializableExtra(
				"alsotrue");
		adddata();
		if (null == menusend || "".equals(menusend)) {
			return;
		}
		adapter = new NewMymenuAdapter(menusend, this);
		expandableListView.setAdapter(adapter);
		for (int i = 0; i < menusend.size(); i++) {
			expandableListView.expandGroup(i);
			for (int j = 0; j < menusend.get(i).tab.size(); j++) {
				map.put(menusend.get(i).tab.get(j).id,
						menusend.get(i).tab.get(j));
				checkmap.put(menusend.get(i).tab.get(j).id, false);
				Log.d("kanyijjjjjjj", "不是" + menusend.get(i).tab.get(j).id);
			}
		}
		if (ShowList.size() > 0) {
			for (int i = 0; i < ShowList.size(); i++) {
				checkmap.put(ShowList.get(i).id, true);
//				Log.d("kanyijjjjjjj", "传过来的" + ShowList.get(i).id);
//				if ("task1201".equals(ShowList.get(i).id)) {
//					check1.setChecked(true);
//				}
//				if ("approval1201".equals(ShowList.get(i).id)) {
//					check2.setChecked(true);
//				}
//				if ("card1201".equals(ShowList.get(i).id)) {
//					check3.setChecked(true);
//				}
//				if ("keyProjects1201".equals(ShowList.get(i).id)) {
//					check4.setChecked(true);
//				}
//				if ("myyj12012".equals(ShowList.get(i).id)) {
//					check5.setChecked(true);
//				}
//				if ("newOpp12013".equals(ShowList.get(i).id)) {
//					check6.setChecked(true);
//				}
//				if ("mywork1201".equals(ShowList.get(i).id)) {
//					check7.setChecked(true);
//				}
//				if ("weixsld1201".equals(ShowList.get(i).id)) {
//					check8.setChecked(true);
//				}
			}
		}
		// imageView = (ImageView) findViewById(R.id.iv1);
	}

	private List<MenuTabModel> menuTabsAll;// 所有该显示的
	private List<MenuTabModel> currentShowList;// 当前九宫格显示的

	private void adddata() {
		// TODO Auto-generated method stub
		menuTabsAll = new ArrayList<MenuTabModel>();
		menuTabsAll.clear();
		currentShowList = new ArrayList<MenuTabModel>();
		currentShowList.clear();

		MenuTabModel tabSchedule = new MenuTabModel();
		tabSchedule.id = "task1201";
		tabSchedule.url = "url:task";
		tabSchedule.tab_style = "style:task";
		tabSchedule.tabStyle = "style:task";
		if ("en".equals(mEns)) {
			tabSchedule.tabName = "Schedules";
			tabSchedule.tab_name = "Schedules";
		}else{
			tabSchedule.tabName = "日程事件";
			tabSchedule.tab_name = "日程事件";
	}
		
		tabSchedule.imageId = "cloudtabtask";
		tabSchedule.objId = "android:task";

		MenuTabModel tabApproval = new MenuTabModel();
		tabApproval.id = "approval1201";
		tabApproval.url = "url:approval";
		tabApproval.tab_style = "style:approval";
		tabApproval.tabStyle = "style:approval";
		if ("en".equals(mEns)) {
			tabApproval.tabName = "Approvals";
			tabApproval.tab_name = "Approvals";
		}else{
			tabApproval.tabName = "待审批";
			tabApproval.tab_name = "待审批";
	}
		tabApproval.imageId = "cloudtab_approval";
		tabApproval.objId = "android:approval";

		MenuTabModel tabScanCard = new MenuTabModel();
		tabScanCard.id = "card1201";
		tabScanCard.url = "url:card";
		tabScanCard.tab_style = "style:card";
		tabScanCard.tabStyle = "style:card";
	
		if ("en".equals(mEns)) {
			tabScanCard.tabName = "Scan business cards";
			tabScanCard.tab_name = "Scan business cards";
		}else{
			tabScanCard.tabName = "扫一扫";
			tabScanCard.tab_name = "扫一扫";
	}
		
		tabScanCard.imageId = "cloudtabscancard";
		tabScanCard.objId = "android:card";

//		MenuTabModel tabCeshi = new MenuTabModel();
//		tabCeshi.id = "keyProjects1201";
//		tabCeshi.url = "url:keyProjects";
//		tabCeshi.tab_style = "style:keyProjects";
//		tabCeshi.tabStyle = "style:keyProjects";
//		tabCeshi.tabName = "重点项目";
//		tabCeshi.tab_name = "重点项目";
//		tabCeshi.imageId = "cloudtabprojects";
//		tabCeshi.objId = "android:keyProjects";
//		MenuTabModel tabCeshi1 = new MenuTabModel();
//		tabCeshi1.id = "myyj12012";
//		tabCeshi1.url = "url:myyj";
//		tabCeshi1.tab_style = "style:myyj";
//		tabCeshi1.tabStyle = "style:myyj";
//		tabCeshi1.tabName = "我的业绩";
//		tabCeshi1.tab_name = "我的业绩";
//		tabCeshi1.imageId = "cloudtab_myyj";
//		tabCeshi1.objId = "android:myyj";
//		MenuTabModel tabCeshi2 = new MenuTabModel();
//		tabCeshi2.id = "newOpp12013";
//		tabCeshi2.url = "url:card3";
//		tabCeshi2.tab_style = "style:newOpp";
//		tabCeshi2.tabStyle = "style:newOpp";
//		tabCeshi2.tabName = "最新潜客";
//		tabCeshi2.tab_name = "最新潜客";
//		tabCeshi2.imageId = "cloudtab_nopp";
//		tabCeshi2.objId = "android:newOpp";
//		MenuTabModel tabCeshi3 = new MenuTabModel();
//		tabCeshi3.id = "mywork1201";
//		tabCeshi3.url = "url:mywork";
//		tabCeshi3.tab_style = "style:mywork";
//		tabCeshi3.tabStyle = "style:mywork";
//		tabCeshi3.tabName = "我的工作";
//		tabCeshi3.tab_name = "我的工作";
//		tabCeshi3.imageId = "cloudtab_mywork";
//		tabCeshi3.objId = "android:mywork";
		MenuTabModel tabCeshi4 = new MenuTabModel();
		tabCeshi4.id = "weixsld1201";
		tabCeshi4.url = "url:weixsld";
		tabCeshi4.tab_style = "style:weixsld";
		tabCeshi4.tabStyle = "style:weixsld";
		if ("en".equals(mEns)) {
			tabCeshi4.tabName = "Selling funnel";
			tabCeshi4.tab_name = "Selling funnel";
		}else{
			tabCeshi4.tabName = "销售漏斗";
			tabCeshi4.tab_name = "销售漏斗";
	}
		
		tabCeshi4.imageId = "cloudtab_weixsld";
		tabCeshi4.objId = "android:weixsld";

		menuTabsAll.add(tabSchedule);
		menuTabsAll.add(tabApproval);
		menuTabsAll.add(tabScanCard);
//		menuTabsAll.add(tabCeshi);
//		menuTabsAll.add(tabCeshi1);
//		menuTabsAll.add(tabCeshi2);
//		menuTabsAll.add(tabCeshi3);
		menuTabsAll.add(tabCeshi4);
		// try {
		// menusend.get(0).tab.addAll(menuTabsAll);
		// } catch (Exception e) {
		// Toast.makeText(this, "获取数据失败，请重新登陆", 1).show();
		// }
		// morenmap.put((Integer)1, tabSchedule);
		// morenmap.put((Integer)2, tabApproval);
		// morenmap.put((Integer)3, tabScanCard);
		// morenmap.put((Integer)4, tabCeshi);
		// morenmap.put((Integer)5, tabCeshi1);
		// morenmap.put((Integer)6, tabCeshi2);
		// morenmap.put((Integer)7, tabCeshi3);
		// morenmap.put((Integer)8, tabCeshi4);
	}

	List<MenuTabModel> listjia;
	// 默认的八个数据处理
	List<MenuTabModel> listjia1 = new ArrayList<MenuTabModel>();;
//网主页传递的数据
	Map<String, MenuTabModel> guodumap = new TreeMap<String, MenuTabModel>();
	//为了排序复制的传递数据
List<String> listpaixu = new ArrayList<String>();
Map<String, MenuTabModel> guodumapnew = new LinkedHashMap<String, MenuTabModel>();
	// Map<Integer, MenuTabModel> morenmap = new HashMap<Integer,
	// MenuTabModel>();

	private void addlistener() {
		// TODO Auto-generated method stub
		// 取消
		tv1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NewMenuFilterActivity.this.finish();
			}
		});
		// 应用
		tv2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				listjia = new ArrayList<MenuTabModel>();
				List<String> listshunxu = new ArrayList<String>();
//				listjia.addAll(listjia1);
				// TODO Auto-generated method stub
				try {
					
				
				if (menusend.size() <= 0) {
					return;
				} else {
					for (int i = 0; i < menusend.size(); i++) {
						for (int j = 0; j < menusend.get(i).tab.size(); j++) {
//							Log.d("shuju","id++"+menusend.get(i).tab.get(j).id);
							if (checkmap.get(menusend.get(i).tab.get(j).id)) {
									Log.d("ksjdsdkfh", "天假"+menusend.get(i).tab.get(j).tab_name);
									 guodumap.put(menusend.get(i).tab.get(j).id,
												menusend.get(i).tab.get(j));
									 listpaixu.add(menusend.get(i).tab.get(j).id);
							}
								
								Log.d("daodizoulenaliaaa",menusend.get(i).tab.get(j).tab_name);
							}
						}

					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				//list去重
				for (int i = 0; i < listpaixu.size(); i++)  //外循环是循环的次数
	            {
	                for (int j = listpaixu.size() - 1 ; j > i; j--)  //内循环是 外循环一次比较的次数
	                {

	                    if (listpaixu.get(i).equals(listpaixu.get(j)))
	                    {
	                    	listpaixu.remove(j);
	                    }

	                }
	            }
				
				
					for (int i = 0; i < listpaixu.size(); i++) {
						Log.d("woshixinde", "list的key：："+map.get(listpaixu.get(i)).tab_name+"::"+guodumap.get(listpaixu.get(i)).tab_name);
						guodumapnew.put(listpaixu.get(i),guodumap.get(listpaixu.get(i)));
					}
					for (String key : guodumapnew.keySet()) {
						Log.d("shujudehoumian", "group的key：："+key+"map的value;;"+map.get(key).tab_name);
						listjia.add(map.get(key));

					}
				for (int i = 0; i < listjia.size(); i++) {
					Log.d("shuju", listjia.get(i).tab_name);
				}

				shouyerefrence shouyerefrence = new shouyerefrence();
				shouyerefrence.list = listjia;
				// CacheManager.getInstance().cacheIgnoreMenu(listjia);
				// #2 设置回退
				EventEngine.post(shouyerefrence);
				NewMenuFilterActivity.this.finish();
			}
		});
	}

//	// 点击事件
//	@Override
//	public boolean onGroupClick(ExpandableListView parent, View v,
//			int groupPosition, long id) {
//		// TODO Auto-generated method stub
//		return false;
//	}

	Map<String, Boolean> checkmap = new HashMap<>();
	boolean istrue = false;

	public class NewMymenuAdapter extends BaseExpandableListAdapter {

		private List<MenuModel> mData;

		private Context mContext;

		public NewMymenuAdapter(List<MenuModel> data, Context mcContext) {
			super();
			this.mData = data;
			this.mContext = mcContext;
			inflater = LayoutInflater.from(mcContext);
		}

		@Override
		public int getGroupCount() {
			return mData.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {

			return mData.get(groupPosition).tab.size();
		}

		@Override
		public MenuModel getGroup(int groupPosition) {
			return mData.get(groupPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		@Override
		public MenuTabModel getChild(int groupPosition, int childPosition) {
			return mData.get(groupPosition).tab.get(childPosition);
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {

			MenuModel menu = mData.get(groupPosition);

			GroupViewHolder holder;
			if (convertView == null) {
//				convertView = LayoutInflater.from(mContext).inflate(
//						R.layout.newgroup_item, null);
				convertView = inflater.inflate(R.layout.newgroup_item, null);
				holder = new GroupViewHolder();
				holder.mGroupName = (TextView) convertView
						.findViewById(R.id.newgroup_name);
				holder.imageview = (ImageView) convertView
						.findViewById(R.id.newgroup_icon);
				convertView.setTag(holder);
			} else {
				holder = (GroupViewHolder) convertView.getTag();
			}
			holder.mGroupName.setText(menu.label);
			Log.d("label", "labelshi" + menu.label);
			if (menu != null) {
				holder.imageview.setImageResource(R.drawable.anglerdown);
			}
			// 点击展开
			if (isExpanded && menu != null) {
				holder.imageview.setImageResource(R.drawable.angleup);
			}
			return convertView;
		}

//		private TextView textView;
//		private CheckBox box;
//		private ImageView menu_image_bg,menu_add_icon;
//		private LinearLayout linearLayout;
		private LayoutInflater inflater;
		@Override
		public View getChildView(final int groupPosition, int childPosition,
								 boolean isLastChild, View convertView, ViewGroup parent) {
			final MenuTabModel childMenu = mData.get(groupPosition).tab
					.get(childPosition);
			ChildViewHolder childViewHolder  = new ChildViewHolder();
			convertView = inflater.inflate(R.layout.newchild_item, null);
			childViewHolder.imageview =(ImageView) convertView.findViewById(R.id.menu_add_icon);
			childViewHolder.mChildName = (TextView) convertView.findViewById(R.id.tv1);
			childViewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.newchild_icon);
			childViewHolder.linearLayout = (LinearLayout) convertView.findViewById(R.id.guanli_ll);
			childViewHolder.checkBox.setTag(childMenu.id);
			try {
				Class drawable = R.drawable.class;
				Field field = drawable.getField(childMenu.imageId+"_1");
				int id = field.getInt(field.getName());
				childViewHolder.imageview.setImageBitmap(null);
				childViewHolder.imageview.setBackgroundResource(id);

			} catch (Exception e) {
				e.printStackTrace();
			}
			childViewHolder.checkBox.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					CheckBox c = (CheckBox) v;
					// 获取当前控件的Tag，即与其绑定的position
					String po = (String) c.getTag();
					// 判断当前控件是否选中
					if (c.isChecked()) {
						// 若选中，就根据绑定的position找到相对应的控件设置状态为turn
						checkmap.put(po, true);
					} else {
						// 若未选中，就根据绑定的position找到相对应的控件设置状态为false
						checkmap.put(po, false);
					}

				}
			});
			childViewHolder.linearLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (StringUtils.isNotBlank(childMenu.objId)
							&& childMenu.objId.startsWith("android:")) {
						if (childMenu.objId.startsWith("android:task")) {// 任务
							Intent intent = new Intent(NewMenuFilterActivity.this,
									ScheduleMainActivity.class);
							startActivity(intent);
						} else if (childMenu.objId.startsWith("android:approval")) {
							// Intent intent2 = new Intent(getActivity(),
							// TaskManagementActivty.class);
							AppContext.indexUrl = UrlManager.getRootUrl()
									+ UrlTools
									.getModuleUrl(mData.get(groupPosition).id, mData.get(groupPosition).label);
							AppContext.urlString = UrlManager.getRootUrl()
									+ "/WeiXin_getmangeAllAppRequest.action";
							Intent intent2 = new Intent(NewMenuFilterActivity.this, TaskManagementActivty.class);
							startActivity(intent2);
						} else if (childMenu.objId.startsWith("android:card")) {
							Intent intent = new Intent(NewMenuFilterActivity.this,
									BusinesscardScanningActivity.class);
							startActivity(intent);
						}else if (childMenu.objId.startsWith("android:weixsld")) {
							AppContext.indexUrl = UrlManager.getRootUrl()
									+ UrlTools
									.getModuleUrl(mData.get(groupPosition).id, mData.get(groupPosition).label);
							AppContext.urlString = UrlManager.getRootUrl()
									+ "/weistdashbord.action?m=weixsld";
							Intent intent = new Intent(NewMenuFilterActivity.this,
									WebViewActivtiy.class);
							startActivity(intent);
						}
					}else{
							Log.d("clickshanping", "闪屏测试:点击跳转第一步");
							AppContext.indexUrl = UrlManager.getRootUrl()
									+ UrlTools.getModuleUrl(mData.get(groupPosition).id, mData.get(groupPosition).label);
							AppContext.urlString = UrlManager.getRootUrl()
									+ UrlTools.getTabsUrl(childMenu, mData.get(groupPosition));
							MenuManager.getInstance().enterMenuDetailOrList(childMenu,
									NewMenuFilterActivity.this);
						}
					}
			});
			childViewHolder.checkBox.setChecked(checkmap.get(childMenu.id));
			childViewHolder.mChildName.setText(childMenu.tab_name);
			Log.d("childmenu", "childMenu" + childMenu.tab_name);

			return convertView;
		}

		class GroupViewHolder {
			TextView mGroupName;
			ImageView imageview;
		}
		class ChildViewHolder {
			TextView mChildName;
			ImageView imageview;
			CheckBox checkBox;
			LinearLayout linearLayout;
		}

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//		switch (buttonView.getId()) {
//		case R.id.check1:
//			// Toast.makeText(NewMenuFilterActivity.this,
//			// "dianji" + menuTabsAll.size(), 1).show();
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(0));
//			} else {
//				listjia1.remove(menuTabsAll.get(0));
//			}
//			break;
//		case R.id.check2:
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(1));
//			} else {
//				listjia1.remove(menuTabsAll.get(1));
//			}
//			break;
//		case R.id.check3:
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(2));
//			} else {
//				listjia1.remove(menuTabsAll.get(2));
//			}
//			break;
//		case R.id.check4:
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(3));
//			} else {
//				listjia1.remove(menuTabsAll.get(3));
//			}
//			break;
//		case R.id.check5:
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(4));
//			} else {
//				listjia1.remove(menuTabsAll.get(4));
//			}
//			break;
//		case R.id.check6:
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(5));
//			} else {
//				listjia1.remove(menuTabsAll.get(5));
//			}
//			break;
//		case R.id.check7:
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(6));
//			} else {
//				listjia1.remove(menuTabsAll.get(6));
//			}
//			break;
//		case R.id.check8:
//			if (isChecked) {
//				listjia1.add(menuTabsAll.get(7));
//			} else {
//				listjia1.remove(menuTabsAll.get(7));
//			}
//			break;
//
//		default:
//			break;
//		}
	}

}
